//
//  HMSinaPicturesView.swift
//  ZJCSina
//
//  Created by 朱建超 on 16/11/18.
//  Copyright © 2016年 itHeiMa. All rights reserved.
//

import UIKit

private let HMSinaPictureViewCollectionCellID = "HMSinaPictureViewCollectionCellID"

class HMSinaPicturesCollectionView: UICollectionView {

    var sinaPictures : [HMSinaPictures]?{
    
        didSet{

            //外界给视图设置数据的时候就会执行
            reloadData()
        }
    
    }
    
    override func awakeFromNib() {
        
        //注册cell
        let pictureCellNib = UINib(nibName: "HMSinaPictureViewCollectionCell", bundle: nil)
        
        self.register(pictureCellNib, forCellWithReuseIdentifier: HMSinaPictureViewCollectionCellID)
        
        //显示数据  实现数据源方法
        self.dataSource = self
        
        //设置代理
        self.delegate = self
        
    }
   

    
}

extension HMSinaPicturesCollectionView : UICollectionViewDataSource,UICollectionViewDelegate{

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
         //实现数据源方法
        return sinaPictures?.count ?? 0
        
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: HMSinaPictureViewCollectionCellID, for: indexPath) as! HMSinaPictureViewCollectionCell
        
        let pictureInfo = sinaPictures![indexPath.item]
        
        cell.picturesInfo = pictureInfo 
        
//        cell.backgroundColor = randomColor()
        
        return cell
        
    }
    
    //实现代理方法
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        //显示图片浏览器
        let browser = SDPhotoBrowser()
        
        //设置容器视图
        browser.sourceImagesContainerView = self
        
        browser.currentImageIndex = indexPath.item
        
        browser.imageCount = sinaPictures?.count ?? 0
        
        //设置代理
        browser.delegate = self
        
        //显示图片浏览器
        browser.show()
    }
    
}

extension HMSinaPicturesCollectionView : SDPhotoBrowserDelegate{

    //返回高质量图片的url对象
    func photoBrowser(_ browser: SDPhotoBrowser!, highQualityImageURLFor index: Int) -> URL! {
        
        let picture = self.sinaPictures?[index]
        
        let url = URL(string: picture?.bmiddle_pic ?? "")
        
        return url
    }
    
    //返回一个占位的图片
    func photoBrowser(_ browser: SDPhotoBrowser!, placeholderImageFor index: Int) -> UIImage! {
        
        //获取cell
        let indexPath = IndexPath(item: index, section: 0)
        
        let cell = self.cellForItem(at: indexPath) as? HMSinaPictureViewCollectionCell
        
        return cell?.pictureView.image
        
    }

}
